<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>服务远程调用(RestTemplate、Feign、Dubbo) | 有求必应</title><meta name="author" content="Mr.wu"><meta name="copyright" content="Mr.wu"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="RestTemplate介绍RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具 RestTemplate 继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口，其中 RestOperations 接口定义了基本的 RESTful 操作，这些操作在 RestTemplate 中都得到了实现。  RestTempl">
<meta property="og:type" content="article">
<meta property="og:title" content="服务远程调用(RestTemplate、Feign、Dubbo)">
<meta property="og:url" content="https://comortgfytry.github.io/pages/RPC%E6%A1%86%E6%9E%B6/%E6%9C%8D%E5%8A%A1%E8%BF%9C%E7%A8%8B%E8%B0%83%E7%94%A8(RestTemplate%E3%80%81Feign%E3%80%81Dubbo).html">
<meta property="og:site_name" content="有求必应">
<meta property="og:description" content="RestTemplate介绍RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具 RestTemplate 继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口，其中 RestOperations 接口定义了基本的 RESTful 操作，这些操作在 RestTemplate 中都得到了实现。  RestTempl">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://comortgfytry.github.io/img/avatar.jpg">
<meta property="article:published_time" content="2023-12-30T02:24:00.000Z">
<meta property="article:modified_time" content="2024-01-05T09:21:34.000Z">
<meta property="article:author" content="Mr.wu">
<meta property="article:tag" content="rpc">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://comortgfytry.github.io/img/avatar.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://comortgfytry.github.io/pages/RPC%E6%A1%86%E6%9E%B6/%E6%9C%8D%E5%8A%A1%E8%BF%9C%E7%A8%8B%E8%B0%83%E7%94%A8(RestTemplate%E3%80%81Feign%E3%80%81Dubbo).html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":300},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":200,"languages":{"author":"作者: Mr.wu","link":"链接: ","source":"来源: 有求必应","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '服务远程调用(RestTemplate、Feign、Dubbo)',
  isPost: true,
  isHome: false,
  isHighlightShrink: undefined,
  isToc: true,
  postUpdate: '2024-01-05 17:21:34'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/mycss.css"><style type="text/css"> #universe {  display: block; position: fixed; margin: 0; padding: 0; border: 0; outline: 0; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 1; } </style><meta name="generator" content="Hexo 6.3.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">63</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">32</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-bookmark"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://api.aqcoder.cn/random')"><nav id="nav"><span id="blog-info"><a href="/" title="有求必应"><span class="site-name">有求必应</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-bookmark"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">服务远程调用(RestTemplate、Feign、Dubbo)</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-12-30T02:24:00.000Z" title="发表于 2023-12-30 10:24:00">2023-12-30</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-01-05T09:21:34.000Z" title="更新于 2024-01-05 17:21:34">2024-01-05</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/RPC%E6%A1%86%E6%9E%B6/">RPC框架</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">804</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>4分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="服务远程调用(RestTemplate、Feign、Dubbo)"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="RestTemplate"><a href="#RestTemplate" class="headerlink" title="RestTemplate"></a>RestTemplate</h1><h2 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h2><p>RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具</p>
<p>RestTemplate 继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口，其中 RestOperations 接口定义了基本的 RESTful 操作，这些操作在 RestTemplate 中都得到了实现。</p>
<p> RestTemplate访问RESTful的三个参数：  </p>
<ul>
<li>url</li>
<li>requestBean:请求参数</li>
<li>ResponseBean.class:HTTP响应转换被转换成的对象类型</li>
</ul>
<h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><h3 id="（1）示例1：Post传递信息"><a href="#（1）示例1：Post传递信息" class="headerlink" title="（1）示例1：Post传递信息"></a>（1）示例1：Post传递信息</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//消费者</span></span><br><span class="line"><span class="meta">@PostMapping(&quot;/testPost&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">postMessage</span><span class="params">(<span class="meta">@RequestParam(&quot;message&quot;)</span>String message, <span class="meta">@RequestParam(&quot;sender&quot;)</span>String sender)</span> &#123;</span><br><span class="line">    <span class="type">String</span> <span class="variable">url</span> <span class="operator">=</span>  <span class="string">&quot;http://mode2/mode2/post&quot;</span>;</span><br><span class="line">    MultiValueMap&lt;String, String&gt; map = <span class="keyword">new</span> <span class="title class_">LinkedMultiValueMap</span>&lt;&gt;();</span><br><span class="line">    map.add(sender,message);</span><br><span class="line"></span><br><span class="line">    HttpEntity&lt;MultiValueMap&lt;String, String&gt;&gt; httpEntity = <span class="keyword">new</span> <span class="title class_">HttpEntity</span>&lt;&gt;(map, <span class="keyword">new</span> <span class="title class_">HttpHeaders</span>());</span><br><span class="line"></span><br><span class="line">    ResponseEntity&lt;String&gt; response = restTemplate.postForEntity(url, httpEntity, String.class);</span><br><span class="line">    <span class="keyword">return</span> response.getBody();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>发送消息的方法有三种:(postForEntity和exchange可以设置请求头)</p>
<ul>
<li><p>postForEntity</p>
</li>
<li><p>postForObject</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">String</span> <span class="variable">result</span> <span class="operator">=</span> template.postForObject(url, map, String.class);</span><br></pre></td></tr></table></figure>
</li>
<li><p>调用exchange方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ResponseEntity&lt;String&gt; response = template.exchange(url, HttpMethod.POST, httpEntity, String.class);</span><br></pre></td></tr></table></figure></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//提供者</span></span><br><span class="line"><span class="meta">@PostMapping(&quot;/post&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">Message1</span><span class="params">(<span class="meta">@RequestBody</span> MultiValueMap&lt;String,String&gt; map)</span>&#123;</span><br><span class="line">    map.keySet().forEach(key -&gt; &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;mode2收到来自&quot;</span> + key + <span class="string">&quot;的消息：&quot;</span> + map.get(key));</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;ack&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="（2）示例2：get请求信息"><a href="#（2）示例2：get请求信息" class="headerlink" title="（2）示例2：get请求信息"></a>（2）示例2：get请求信息</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//消费者</span></span><br><span class="line"><span class="meta">@GetMapping(&quot;/testGet&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">getMessage</span><span class="params">(<span class="meta">@RequestParam(&quot;sender&quot;)</span>String sender)</span> &#123;</span><br><span class="line">    <span class="type">String</span> <span class="variable">url</span> <span class="operator">=</span>  <span class="string">&quot;http://mode2/mode2/get/&#123;sender&#125;&quot;</span>;</span><br><span class="line"></span><br><span class="line">    HashMap&lt;String, String&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">    map.put(<span class="string">&quot;sender&quot;</span>, sender);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> restTemplate.getForObject(url, String.class, map);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//提供者</span></span><br><span class="line"><span class="meta">@GetMapping(&quot;/get/&#123;sender&#125;&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">Message2</span><span class="params">(<span class="meta">@PathVariable(&quot;sender&quot;)</span> String sender)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> messages.getMessageList().get(sender);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="（3）示例3：put修改信息"><a href="#（3）示例3：put修改信息" class="headerlink" title="（3）示例3：put修改信息"></a>（3）示例3：put修改信息</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//消费者</span></span><br><span class="line"><span class="meta">@PutMapping(&quot;/testPut&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">putMessage</span><span class="params">(<span class="meta">@RequestParam(&quot;target&quot;)</span>String target, <span class="meta">@RequestParam(&quot;content&quot;)</span>String content)</span> &#123;</span><br><span class="line">    HashMap&lt;String, String&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">    map.put(<span class="string">&quot;target&quot;</span>, target);</span><br><span class="line"></span><br><span class="line">    <span class="type">String</span> <span class="variable">url</span> <span class="operator">=</span>  <span class="string">&quot;http://mode2/mode2/put/&#123;target&#125;&quot;</span>;</span><br><span class="line">    System.out.println(content);</span><br><span class="line">    <span class="comment">//解决中文乱码</span></span><br><span class="line">    List&lt;HttpMessageConverter&lt;?&gt;&gt; list = restTemplate.getMessageConverters();</span><br><span class="line">    <span class="keyword">for</span> (HttpMessageConverter converter : list) &#123;</span><br><span class="line">        <span class="keyword">if</span> (converter <span class="keyword">instanceof</span> StringHttpMessageConverter) &#123;</span><br><span class="line">            ((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    restTemplate.put(url, content, map);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//生产者</span></span><br><span class="line"><span class="meta">@PutMapping(&quot;/put/&#123;target&#125;&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">Message3</span><span class="params">(<span class="meta">@PathVariable(&quot;target&quot;)</span>String target, <span class="meta">@RequestBody</span> String content)</span> &#123;</span><br><span class="line">    System.out.println(content);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="（3）示例4：delete与get相似"><a href="#（3）示例4：delete与get相似" class="headerlink" title="（3）示例4：delete与get相似"></a>（3）示例4：delete与get相似</h3><h1 id="Feign"><a href="#Feign" class="headerlink" title="Feign"></a>Feign</h1><p>声明式的http客户端</p>
<h2 id="使用-1"><a href="#使用-1" class="headerlink" title="使用"></a>使用</h2><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-openfeign<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>io.github.openfeign<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>feign-httpclient<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@FeignClient(&quot;mode2&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Mode2Client</span> &#123;</span><br><span class="line">    <span class="meta">@PostMapping(&quot;/mode2/post&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">postMessage</span><span class="params">(MultiValueMap&lt;String, String&gt; map)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/mode2/get/&#123;sender&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">queryMessage</span><span class="params">(<span class="meta">@PathVariable(&quot;sender&quot;)</span>String sender)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PutMapping(&quot;/mode2/put/&#123;target&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">putMessage</span><span class="params">(<span class="meta">@PathVariable(&quot;target&quot;)</span>String target,String content)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//POST</span></span><br><span class="line"><span class="meta">@PostMapping(&quot;/testPostFE&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">postMessageFE</span><span class="params">(<span class="meta">@RequestParam(&quot;message&quot;)</span>String message, <span class="meta">@RequestParam(&quot;sender&quot;)</span>String sender)</span> &#123;</span><br><span class="line">    MultiValueMap&lt;String, String&gt; map = <span class="keyword">new</span> <span class="title class_">LinkedMultiValueMap</span>&lt;&gt;();</span><br><span class="line">    map.add(sender, message);</span><br><span class="line">    <span class="keyword">return</span> mode2Client.postMessage(map);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//GET</span></span><br><span class="line"><span class="meta">@GetMapping(&quot;/testGetFE&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">getMessageFE</span><span class="params">(<span class="meta">@RequestParam(&quot;sender&quot;)</span>String sender)</span> &#123;</span><br><span class="line"><span class="keyword">return</span> mode2Client.queryMessage(sender);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@PutMapping(&quot;/testPutFE&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">putMessageFE</span><span class="params">(<span class="meta">@RequestParam(&quot;target&quot;)</span>String target, <span class="meta">@RequestParam(&quot;content&quot;)</span>String content)</span> &#123;</span><br><span class="line">    mode2Client.putMessage(target, content);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="feign底层客户端实现"><a href="#feign底层客户端实现" class="headerlink" title="feign底层客户端实现"></a>feign底层客户端实现</h2><p>默认是urlconnection，不支持连接池。可以用httpclient替换，支持连接池</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring.cloud.openfeign.httpclient.enabled</span>=<span class="string">true</span></span><br><span class="line"><span class="attr">spring.cloud.openfeign.httpclient.max-connections</span>=<span class="string">200</span></span><br><span class="line"><span class="attr">spring.cloud.openfeign.httpclient.max-connections-per-route</span>=<span class="string">50</span></span><br></pre></td></tr></table></figure>

<h2 id="feign的最佳实现"><a href="#feign的最佳实现" class="headerlink" title="feign的最佳实现"></a>feign的最佳实现</h2><h3 id="定义统一父接口给FeignClient和提供者的controller"><a href="#定义统一父接口给FeignClient和提供者的controller" class="headerlink" title="定义统一父接口给FeignClient和提供者的controller"></a>定义统一父接口给FeignClient和提供者的controller</h3><p>缺点：</p>
<ul>
<li>紧耦合</li>
<li>父接口参数列表中的映射不会被继承</li>
</ul>
<h2 id="将feignclient抽取为独立的模块"><a href="#将feignclient抽取为独立的模块" class="headerlink" title="将feignclient抽取为独立的模块"></a>将feignclient抽取为独立的模块</h2></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://comortgfytry.github.io">Mr.wu</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://comortgfytry.github.io/pages/RPC%E6%A1%86%E6%9E%B6/%E6%9C%8D%E5%8A%A1%E8%BF%9C%E7%A8%8B%E8%B0%83%E7%94%A8(RestTemplate%E3%80%81Feign%E3%80%81Dubbo).html">https://comortgfytry.github.io/pages/RPC%E6%A1%86%E6%9E%B6/%E6%9C%8D%E5%8A%A1%E8%BF%9C%E7%A8%8B%E8%B0%83%E7%94%A8(RestTemplate%E3%80%81Feign%E3%80%81Dubbo).html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://comortgfytry.github.io" target="_blank">有求必应</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/rpc/">rpc</a><a class="post-meta__tags" href="/tags/java/">java</a></div><div class="post_share"><div class="social-share" data-image="/img/avatar.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/pages/%E8%BD%AF%E4%BB%B6%E6%9E%B6%E6%9E%84/%E8%BD%AF%E4%BB%B6%E6%9E%B6%E6%9E%84%E5%A4%8D%E4%B9%A0.html" title="软件架构复习"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">软件架构复习</div></div></a></div><div class="next-post pull-right"><a href="/pages/%E7%AE%97%E6%B3%95/%E7%9F%A9%E9%98%B5/%E7%9F%A9%E9%98%B5%E7%BD%AE%E9%9B%B6.html" title="矩阵置零"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">矩阵置零</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Mr.wu</div><div class="author-info__description">分享知识</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">63</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">32</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/xxxxxx" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://blog.csdn.net/blue_gym" target="_blank" title="CSDN"><i class="fa fa-book-open"></i></a><a class="social-icon" href="mailto:shouwangyinying@163.com" target="_blank" title="Email"><i class="fas fa-envelope-open-text"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">Nice to meet you. please get website connection by Ctrl + F5</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#RestTemplate"><span class="toc-number">1.</span> <span class="toc-text">RestTemplate</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%8B%E7%BB%8D"><span class="toc-number">1.1.</span> <span class="toc-text">介绍</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8"><span class="toc-number">1.2.</span> <span class="toc-text">使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%EF%BC%881%EF%BC%89%E7%A4%BA%E4%BE%8B1%EF%BC%9APost%E4%BC%A0%E9%80%92%E4%BF%A1%E6%81%AF"><span class="toc-number">1.2.1.</span> <span class="toc-text">（1）示例1：Post传递信息</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%EF%BC%882%EF%BC%89%E7%A4%BA%E4%BE%8B2%EF%BC%9Aget%E8%AF%B7%E6%B1%82%E4%BF%A1%E6%81%AF"><span class="toc-number">1.2.2.</span> <span class="toc-text">（2）示例2：get请求信息</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%EF%BC%883%EF%BC%89%E7%A4%BA%E4%BE%8B3%EF%BC%9Aput%E4%BF%AE%E6%94%B9%E4%BF%A1%E6%81%AF"><span class="toc-number">1.2.3.</span> <span class="toc-text">（3）示例3：put修改信息</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%EF%BC%883%EF%BC%89%E7%A4%BA%E4%BE%8B4%EF%BC%9Adelete%E4%B8%8Eget%E7%9B%B8%E4%BC%BC"><span class="toc-number">1.2.4.</span> <span class="toc-text">（3）示例4：delete与get相似</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Feign"><span class="toc-number">2.</span> <span class="toc-text">Feign</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-1"><span class="toc-number">2.1.</span> <span class="toc-text">使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#feign%E5%BA%95%E5%B1%82%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.2.</span> <span class="toc-text">feign底层客户端实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#feign%E7%9A%84%E6%9C%80%E4%BD%B3%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.3.</span> <span class="toc-text">feign的最佳实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89%E7%BB%9F%E4%B8%80%E7%88%B6%E6%8E%A5%E5%8F%A3%E7%BB%99FeignClient%E5%92%8C%E6%8F%90%E4%BE%9B%E8%80%85%E7%9A%84controller"><span class="toc-number">2.3.1.</span> <span class="toc-text">定义统一父接口给FeignClient和提供者的controller</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B0%86feignclient%E6%8A%BD%E5%8F%96%E4%B8%BA%E7%8B%AC%E7%AB%8B%E7%9A%84%E6%A8%A1%E5%9D%97"><span class="toc-number">2.4.</span> <span class="toc-text">将feignclient抽取为独立的模块</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/pages/%E7%AE%97%E6%B3%95/%E6%99%AE%E9%80%9A%E6%95%B0%E7%BB%84/%E7%BC%BA%E5%A4%B1%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E6%AD%A3%E6%95%B0.html" title="缺失的第一个正数">缺失的第一个正数</a><time datetime="2024-01-06T13:48:58.072Z" title="发表于 2024-01-06 21:48:58">2024-01-06</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/pages/%E7%AE%97%E6%B3%95/%E7%9F%A9%E9%98%B5/%E7%9F%A9%E9%98%B5%E7%BD%AE%E9%9B%B6.html" title="矩阵置零">矩阵置零</a><time datetime="2024-01-06T13:48:58.070Z" title="发表于 2024-01-06 21:48:58">2024-01-06</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/pages/RPC%E6%A1%86%E6%9E%B6/%E6%9C%8D%E5%8A%A1%E8%BF%9C%E7%A8%8B%E8%B0%83%E7%94%A8(RestTemplate%E3%80%81Feign%E3%80%81Dubbo).html" title="服务远程调用(RestTemplate、Feign、Dubbo)">服务远程调用(RestTemplate、Feign、Dubbo)</a><time datetime="2023-12-30T02:24:00.000Z" title="发表于 2023-12-30 10:24:00">2023-12-30</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/pages/%E8%BD%AF%E4%BB%B6%E6%9E%B6%E6%9E%84/%E8%BD%AF%E4%BB%B6%E6%9E%B6%E6%9E%84%E5%A4%8D%E4%B9%A0.html" title="软件架构复习">软件架构复习</a><time datetime="2023-12-23T15:50:20.000Z" title="发表于 2023-12-23 23:50:20">2023-12-23</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/pages/%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE/%E6%90%9C%E7%B4%A2%E4%BA%8C%E7%BB%B4%E7%9F%A9%E9%98%B5.html" title="搜索二维矩阵 - 算法 - 二分查找">搜索二维矩阵 - 算法 - 二分查找</a><time datetime="2023-12-04T04:50:20.000Z" title="发表于 2023-12-04 12:50:20">2023-12-04</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://api.aqcoder.cn/random')"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2024 By Mr.wu</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><div class="js-pjax"></div><canvas id="universe"></canvas>'<script src="/js/universe.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div><script async>window.onload=function(){var a=document.createElement('script'),b=document.getElementsByTagName('script')[0];a.type='text/javascript',a.async=!0,a.src='/sw-register.js?v='+Date.now(),b.parentNode.insertBefore(a,b)};</script></body></html>